<?php
require_once("../../../config.inc.php");
$isReloadable = false;
require_once("../../../app/_inc/include.php");
require_once("./_inc/entityFunction.php");

$errMsg = sxREQ('msg');
$aSA = array();
$objUser = $_SESSION[USEROBJ];
$aDataArea = $objUser->getDataArea();
$dataArea = (sxREQ('da')=='')?sxREQ('data_area'):sxREQ('da');

if($dataArea==''){
	$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".urlencode(_t("missing data-area."));
	serverRedir($url);
}
if(!isset($aDataArea[$dataArea])){
	$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".
		urlencode(_t("user disalbled for data-area '%s'",$dataArea));
	serverRedir($url);
}
$entity = "";
$description = "";
$note = "";
$physical_param = "";
$indef_article = 'a';
$sSQL = "SELECT subject_area FROM subject_area " .
		" WHERE data_area='$dataArea' " .
		" ORDER BY subject_area";
$objSDAO->query($sSQL,"SA");
while($row=$objSDAO->fetch('SA')) {
	$aSA['sa_'.$row['subject_area']] = false;
}

if(isset($_REQUEST["reqtype"]) && $_REQUEST["reqtype"] == "save"){
	$errMsg .= entityIns();
	$entity = sxREQUEST("entity");
	$data_area = sxREQUEST("data_area");
	$description = sxREQUEST("description");
	$indef_article = sxREQUEST("indef_article");
	$note = sxREQUEST("note");
	$physical_param = sxREQUEST("physical_param");
	foreach($_REQUEST as $nome => $val) {
		if (substr($nome,0,3) != 'sa_') continue;
		$aSA[$nome] = true;
	}
}
/*
$sSQL = "SELECT * FROM data_area $sCondDataArea ORDER BY data_area";
if(!$queryDataArea = $objSDAO->query($sSQL)){
	$errMsg .= $objSDAO->error;
	$errCode .= $objSDAO->errno;
}
*/
//output HTML
$aOpz = array("kMenu"=>'dam', "isReloadable"=>$isReloadable);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript" src="../../_jsc/form.js"></script>  
<script language="JavaScript" type="text/javascript">
	function objFrmSave(){
		try{
			var objFrm = document.getElementById("objFrm");
			var objDA =  document.getElementById("data_area");
			var objEnt =  document.getElementById("entity");
			var objMessArea =  document.getElementById("messArea");
			var errMsg = "";
			if(objDA.value == ""){
				errMsg += "<?php echo _t("missing data-area")?><br>";
				objDA.className = "inpt01";
				objDA.focus();
			}else{
				objDA.className = "inpt01";
			}
			if(objEnt.value == ""){
				errMsg += "<?php echo _t("missing name")?><br>";			
				objEnt.className = "inpt01";
				objEnt.focus();
			}else{
				objEnt.className = "inpt01";
			}
			if(errMsg == ""){
				objFrm.submit();
			}else{
				objMessArea.innerHTML = errMsg;
			}	
		}catch(e){
			raiseError(e.description, "save new entity");
		}	
	}
</script>
  
<?php
echo(bodyHTML($aOpz));
$sSQL = "SELECT description FROM data_area WHERE data_area = '$dataArea' ";
$query = $objSDAO->query($sSQL,'da');
if (!$rowDA = $objSDAO->fetch('da')) {
	$url = $_SESSION[USEROBJ]->getHistory(-1, true)."&msg=".urlencode(_t("data-area '%s' not found",$dataArea));
	serverRedir($url);
}
echo("<table width=\"100%\" cellpadding=\"03\" cellspacing=\"0\">");
echo("<tr>" .
		"<td class=\"labl01\" width='10%'>Data-Area: </td>" .
		"<td class=\"text01\" width='90%'><a class='text01' href='../area/dataAreaView.php?da=$dataArea&xsn=".XSN.
			"' title='"._t('Data-Area view')."'>$dataArea</a>' - ".
			sxHE($rowDA['description'])."</td></tr>");
echo("</table>");
$aCmd = array("insEnt"=>array("pag"=>"javascript:objFrmSave()",
										"title"=>_t("Salva i dati"),
										"text"=>_t("salva")),
					"back"=>array("pag"=>$objUser->getHistory(0, false),
										"title"=>$objUser->getHistoryText(0),
										"text"=>$objUser->getHistoryText(0))
					);
echo(commandsHTML($aCmd));	
//form inserimento dati
echo("<form name=\"objFrm\" id=\"objFrm\" action=\"entityIns.php\" method=\"POST\">");
echo("<input type=\"hidden\" name=\"reqtype\" id=\"reqtype\" value=\"save\">");
echo("<input type=\"hidden\" name=\"xsn\" value=\"".XSN."\">");
echo("<input type=\"hidden\" name=\"data_area\" id=\"data_area\" value=\"$dataArea\">");
echo("<table width=\"100%\" cellpadding=\"3\" cellspacing=\"2\">\n");
echo("<tr>" .
			"<td class=\"titl01\" colspan=\"2\">"._t("Entity")."</td>" .
		"</tr>\n");
echo("</td></tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("entity")."*</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"entity\" id=\"entity\" maxlength=\"32\" value=\"$entity\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Description")."</td>");
echo("<td class=\"text01\">");
$aVal = array("a"=>"a","an"=>"an");
echo getHTMLSelect('indef_article', $aVal, $indef_article);			
echo("<input class=\"inpt01\" type=\"text\" name=\"description\" id=\"description\" maxlength=\"80\" size=\"80\" value=\"".sxHE($description)."\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Subject-Area")."</td>".
			"<td class=\"text01\">\n");
foreach($aSA as $nome => $checked) {
	echo("<input class=\"inpt01\" type=\"checkbox\" name=\"$nome\" id=\"$nome\" value=\"Y\" ".
		(($checked)?'CHECKED':'').">" .substr($nome,3)."<br>\n");
}
echo("</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Note")."</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"note\" id=\"note\" cols=\"80\" rows=\"8\">".sxHE($note)."</textarea></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Physical parameters")."</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"physical_param\" id=\"physical_param\" cols=\"80\" rows=\"8\">".sxHE($physical_param)."</textarea></td>" .
		"</tr>\n");
echo("</table>");
echo("</form>");
echo(commandsHTML($aCmd));
echo(footerHTML());
$objSDAO->close();
exit();

function entityIns(){
	global $objSDAO;
	$errMsg = "";
	$_REQUEST["entity"] = strtolower(trim($_REQUEST["entity"]));
	if(!isset($_REQUEST["entity"]) || $_REQUEST["entity"] == "")
		$errMsg .= _t("missing name");
	if(!isset($_REQUEST["data_area"]) || $_REQUEST["data_area"] == "")
		$errMsg .= _t("missing Data-Area");
	if(ereg("[^a-z0-9_]",$_REQUEST["entity"]))
		$errMsg .= _t("name charaters not allowed").".<br>";
	if(strpos($_REQUEST["entity"], " ") !== false)
		$errMsg .= _t("name - space pot allowed").".<br>";
	
	if($errMsg != "")
		return $errMsg;
	
	//controllo che l'entity non esista gi@
	$sSQL = "SELECT count(*) as numentity FROM entity WHERE entity='".$_REQUEST["data_area"]."_".$_REQUEST["entity"]."'";
	$numEntity = 0;
	$objSDAO->query($sSQL,"test");
	$row = $objSDAO->fetch("test");
	if($row["numentity"] != 0)
		$errMsg .= _t("existing entity");
		
	if($errMsg != ""){return $errMsg;}
	if(trim($_REQUEST["description"])=="")  $_REQUEST["description"]= $_REQUEST["entity"];
	$sSQL = "INSERT INTO " .
			"entity " .
			"(entity, " .
			"data_area, " .
			"description, " .
			"indef_article, " .
			"note, " .
			"physical_param)" .
			"VALUES('".sxRAS("data_area").'_'.sxRAS("entity")."', " .
			"'".sxRAS("data_area")."', " .
			"'".sxRAS("description")."', " .
			"'".sxRAS("indef_article")."', " .
			"'".sxRAS("note")."', " .
			"'".sxRAS("physical_param")."'" .
			")";	
	$objSDAO->query($sSQL,"ins");

	foreach($_REQUEST as $nome => $val) {
		if (substr($nome,0,3) != 'sa_') continue;
		$sSQL = "INSERT INTO subject_area_entity (data_area, subject_area, entity) VALUES (" .
				"'".sxRAS("data_area")."', '".substr($nome,3)."', '".sxRAS("data_area").'_'.sxRAS("entity")."')";	
		$objSDAO->query($sSQL,"upd");			
	}
	logRecord("310", _t("Inserita l'entity")." '".addslashes(sxGPC($_REQUEST["data_area"]))."_".addslashes(sxGPC($_REQUEST["entity"])."' "._t("nell'area dati")." '".addslashes(sxGPC(strtolower($_REQUEST["data_area"])))."'"));
	$url = "entityView.php?ent=".$_REQUEST["data_area"]."_".$_REQUEST["entity"]."&da=".$_REQUEST["data_area"]."&xsn=".XSN;
	//$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
	exit();
}
